﻿Imports Trinkets.Core

Public Class LookupWindow

    Private _database As CsvDatabase = Nothing

    Private _table As TableSchema = Nothing

    Private _selectedRecord As BaseEntity = Nothing

    Private Sub New(ByVal database As CsvDatabase, _
                    ByVal table As TableSchema, _
                    ByVal currentSelection As BaseEntity)

        InitializeComponent()
        Me._database = database
        Me._table = table
        Me._selectedRecord = currentSelection

        ' Load rows into the data grid
        DataGridManager.Update(Me.DataGrid, database, table)
        Dim AllRows As BaseEntity() = Me.DataGrid.ItemsSource

        ' Set the selected row
        If currentSelection IsNot Nothing Then
            Dim PrimaryKeyValue As String = table.GetPrimaryKeyValue(currentSelection)
            For RowIndex As Integer = 0 To AllRows.Length - 1
                Dim Entity As BaseEntity = AllRows(RowIndex)
                If PrimaryKeyValue = table.GetPrimaryKeyValue(Entity).ToString Then
                    Me.DataGrid.SelectedIndex = RowIndex
                    Exit For
                End If
            Next
        End If

    End Sub

    Public Shared Function RequestRecord(ByVal database As CsvDatabase, _
                                         ByVal table As TableSchema, _
                                         Optional ByVal currentSelection As BaseEntity = Nothing) As BaseEntity

        ' Show the lookup form
        Dim Form As New LookupWindow(database, table, currentSelection)
        Form.ShowDialog()

        ' Return the selected record
        Return Form._selectedRecord

    End Function

    Private Sub SelectButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles SelectButton.Click

        Me._selectedRecord = Me.DataGrid.SelectedItem
        Me.DialogResult = True

    End Sub

    Private Sub ClearButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles ClearButton.Click

        Me._selectedRecord = Nothing
        Me.DialogResult = True

    End Sub

    Private Sub OpenButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles OpenButton.Click

        ' TODO: Selected record not correct (ever?)
        Dim EditWindow As EditWindow = WindowGenerator.GenerateEditWindow(_database, _table, Me._selectedRecord)
        EditWindow.ShowDialog()
        ' TODO: Update this form, if changes occured

    End Sub

    Private Sub CancelButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles CancelButton.Click
        Me.DialogResult = False
    End Sub

End Class
